package org.nextive.android.weightapp.db;


import org.nextive.android.weightapp.entities.Weight;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class WeightDAO 
{
	private DbOpenHelper dbOpenHelper;
    private SQLiteDatabase database;
    private final Context context;
    
    public static final String WEIGHT_ID = "_id";
    public static final String WEIGHT_DATE = "date";
    public static final String WEIGHT_WEIGHT = "weight";
	
	public WeightDAO(Context context)
	{
		this.context = context;
	}
	
	public void open()
	{
		dbOpenHelper = new DbOpenHelper(context);
		database = dbOpenHelper.getWritableDatabase();
	}
	
	public void close()
	{
		dbOpenHelper.close();
	}
	
	public long insertWeight(Weight weight)
	{
		ContentValues values = new ContentValues();
		values.put(WEIGHT_DATE, weight.getDate());
		values.put(WEIGHT_WEIGHT, weight.getWeight());
		return database.insert(DbOpenHelper.TABLE_WEIGHTS, null, values);
	}
	
	public Cursor findAll() 
	{
        return database.query(DbOpenHelper.TABLE_WEIGHTS, new String[] {WEIGHT_ID, WEIGHT_DATE,
                WEIGHT_WEIGHT}, null, null, null, null, WEIGHT_DATE);
    }
	
	public Cursor findByDate(String date) 
	{
        return database.query(DbOpenHelper.TABLE_WEIGHTS, new String[] {WEIGHT_ID, WEIGHT_DATE,
                WEIGHT_WEIGHT}, WEIGHT_DATE + "=" + "'"+date+"'", null, null, null, WEIGHT_DATE);
    }
	
	public Cursor findSinceDate(String date) 
	{
        return database.query(DbOpenHelper.TABLE_WEIGHTS, new String[] {WEIGHT_ID, WEIGHT_DATE,
                WEIGHT_WEIGHT}, WEIGHT_DATE + ">=" + "'"+date+"'", null, null, null, WEIGHT_DATE);
    }
	
	public boolean delete(long id) 
	{
		return database.delete(DbOpenHelper.TABLE_WEIGHTS, WEIGHT_ID + "=" + id, null) > 0;
	}
	
	public long update(Weight weight)
	{
		ContentValues values = new ContentValues();
		values.put(WEIGHT_DATE, weight.getDate());
		values.put(WEIGHT_WEIGHT, weight.getWeight());
		return database.update(DbOpenHelper.TABLE_WEIGHTS, values, WEIGHT_ID + "=" + weight.getId(), null);
	}
}
